package com.cjjd.c.feature.home.chekin.select_people;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cjjd.c.EventBusKeys;
import com.cjjd.c.R;
import com.cjjd.c.ShareKeys;
import com.cjjd.c.base.ActionBarActivity;
import com.cjjd.c.bean.HttpResult;
import com.cjjd.c.bean.ListResult;
import com.cjjd.c.bean.TravellerListBean;
import com.cjjd.c.feature.home.chekin.select_detail.SelectHomeActivity;
import com.cjjd.c.http.CallbackImpl;
import com.cjjd.c.http.JsonUtils;
import com.cjjd.c.utils.CommonUtil;
import com.cjjd.c.utils.LogUtil;
import com.cjjd.c.utils.SharePrefUtil;
import com.cjjd.c.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/9/24.
 */

public class SelectPeopleActivity extends ActionBarActivity {


    @Bind(R.id.rl_self)
    RelativeLayout rlSelf;
    @Bind(R.id.checkbox_self)
    CheckBox checkboxSelf;

    @Bind(R.id.listview)
    ListView listview;

    public static int SELECT_SIGNAL = 0x00000001;
    public static int SELECT_MULTI = 0x00000002;
    public static int SELECT_MULTI_OF_ONE = 0x00000003;
    private int select_type = 0;

    private String orderMainUuid;
    private String orderDetailUuid;
    private SelectPeopleAdapter selectPeopleAdapter;
    private ArrayList<TravellerListBean> dataList = new ArrayList<>();

    private ArrayList<TravellerListBean> selectedTravellerList = new ArrayList<>();

    private ArrayList<String> orderDetailUuidslist = new ArrayList<>();

    private TravellerListBean selfBean;
    private int unSelectRoomNum;

    @Override
    public Object getTitleString() {
        return "选择入住人";
    }

    @Override
    public int getContentView() {
        return R.layout.fragment_select_people;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        getIntentData();
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();

        getPassangerList();
    }

    private void getIntentData() {

//        Intent intent = new Intent(mContext, SelectPeopleActivity.class);
//        intent.putExtra("select_style",SelectPeopleActivity.SELECT_MULTI);
//        intent.putExtra("unSelectNum",unSelectNum);
//        intent.putStringArrayListExtra("orderDetailUuidslist",orderDetailUuidslist);
//        mContext.startActivity(intent);

        select_type = getIntent().getIntExtra("select_style", 0);
        LogUtil.e("xyd", "select_type = " + select_type);
        LogUtil.e("dada", "select_type = " + select_type);
        orderMainUuid = getIntent().getStringExtra("orderMainUuid");
        LogUtil.e("xyd", "orderMainUuid = " + orderMainUuid);
        orderDetailUuid = getIntent().getStringExtra("orderDetailUuid");
        LogUtil.e("xyd", "unSelectRoomNum = " + unSelectRoomNum);
        orderDetailUuidslist = getIntent().getStringArrayListExtra("orderDetailUuidslist");
                unSelectRoomNum = getIntent().getIntExtra("unSelectNum", 0);

        LogUtil.e("xyd", "orderDetailUuidslist = " + orderDetailUuidslist.size());
    }

    private void getPassangerList() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("nowPage", 1 + "");
        h1.put("pageShow", 20 + "");
        Call<HttpResult<ListResult<TravellerListBean>>> getPassangerList = service.getPassangerList(JsonUtils.convertParam("getPassangerList", h1));
        getPassangerList.enqueue(new CallbackImpl<ListResult<TravellerListBean>>() {
            @Override
            public void responseSuccess(Call<HttpResult<ListResult<TravellerListBean>>> call, Response<HttpResult<ListResult<TravellerListBean>>> response) {
                if (dataList.size() > 0) {
                    dataList.clear();
                }
                dataList.addAll(response.body().getData().dataList);

                for (int i = 0; i < dataList.size(); i++) {
                    if ("1".equals(dataList.get(i).isMyself)) {
                        selfBean = dataList.get(i);
                        rlSelf.setVisibility(View.VISIBLE);
                    }
                }
                if (selfBean != null) {
                    dataList.remove(selfBean);
                }

                selectPeopleAdapter.notifyDataSetChanged();
                CommonUtil.setListViewHeightBasedOnChildren(listview);
            }
        });

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {
        if (EventBusKeys.endSelectHomeMulti.equals(event)) {
            finish();
        }
    }

    private void initView() {


        View headerView = LayoutInflater.from(mContext).inflate(R.layout.item_header_information, listview, false);
        TextView tvName = (TextView) headerView.findViewById(R.id.tv_name);
        tvName.setText("新增常用旅客");
        headerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, AddTravellerActivity.class);
                startActivity(intent);
            }
        });
        listview.addHeaderView(headerView);

        rlSelf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int num=0;
                for (int i=0;i<dataList.size();i++){
                    if(dataList.get(i).isSelected){
                        num++;
                    }
                }
                if(num>=unSelectRoomNum){
                    ToastUtil.showShortToast(mContext,"不能选择更多了");
                    return;
                }

                // before selece self , judge if had selected all unLived room
                int unSelectNum = -1;
                for (TravellerListBean itemBean : dataList) {
                    if (itemBean.isSelected) unSelectNum = unSelectRoomNum - 1;
                }

                if (unSelectNum == 0) {
                    ToastUtil.showShortToast(mContext,"不能选择更多了");
                } else {
                    selfBean.isSelected = !selfBean.isSelected;
                    checkboxSelf.setChecked(selfBean.isSelected);
                }


            }
        });

        selectPeopleAdapter = new SelectPeopleAdapter(mContext);
        selectPeopleAdapter.setSelectType(select_type);
        selectPeopleAdapter.setUnselectNum(unSelectRoomNum);
        selectPeopleAdapter.setData(dataList);
        listview.setAdapter(selectPeopleAdapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // position 从 0 开始, 如果有 header  从 headerview算起
                LogUtil.e("xyd", "点击的条目是: " + position);
                int headerViewNum = listview.getHeaderViewsCount();
                if (select_type == SelectPeopleActivity.SELECT_MULTI) {
                    // 可多选
                    int selectNum = 0;
                    // judge if selfbean had selected
                    if (selfBean != null&& selfBean.isSelected){
                        selectNum++;
                    }
                    for (TravellerListBean item : dataList) {
                        if (item.isSelected) selectNum++;
                    }

                    //dada change
                    if(dataList.get(position-headerViewNum).isSelected){
                        dataList.get(position-headerViewNum).isSelected=false;
                    }else{
                        if (!dataList.get(position - headerViewNum).isSelected && selectNum >= unSelectRoomNum) {
                            ToastUtil.showToast("不能选择更多了");
                        }else{
                            dataList.get(position - headerViewNum).isSelected = true;

                        }
                    }

//                    if (!dataList.get(position - headerViewNum).isSelected && selectNum >= unSelectRoomNum) {
//                        ToastUtil.showToast("不能选择更多了");
//                    } else if (dataList.get(position - headerViewNum).isSelected) {
//                        dataList.get(position - headerViewNum).isSelected = false;
//                    } else if (!dataList.get(position - headerViewNum).isSelected) {
//                    }
                    selectPeopleAdapter.notifyDataSetChanged();
                } else if (select_type == SelectPeopleActivity.SELECT_SIGNAL) {
                    // 只可单选
                    for (TravellerListBean item : dataList) {
                        item.isSelected = false;
                        LogUtil.e("xyd", "设置为未选中");
                    }
                    dataList.get(position - headerViewNum).isSelected = true;
                    selectPeopleAdapter.notifyDataSetChanged();
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.btn_next)
    public void onViewClicked() {
        LogUtil.e("xyd", "点击了下一步");
        if (selectedTravellerList.size() > 0) {
            selectedTravellerList.clear();
        }
        if (checkboxSelf.isChecked()) {
            selectedTravellerList.add(selfBean);
        }
        for (TravellerListBean itemBean : dataList) {
            if (itemBean.isSelected) {
                selectedTravellerList.add(itemBean);
            }
        }

        if ((select_type == SELECT_SIGNAL || select_type == SELECT_MULTI_OF_ONE)
                && selectedTravellerList.size() == 0) {
            ToastUtil.showToast("请选择入住人");
        } else if ((select_type == SELECT_SIGNAL || select_type == SELECT_MULTI_OF_ONE)
                && selectedTravellerList.size() > 1) {
            ToastUtil.showToast("只能选择一个入住人");
        } else if (select_type == SELECT_SIGNAL && selectedTravellerList.size() == 1) {
            // 处理单个人选(两种情况，一种是多人房间，但是单人选，一种是单人房间)
            LogUtil.e("xyd", "去选房");
            goToSelectHomePage(select_type);
        } else if (select_type == SELECT_MULTI) {
            if (selectedTravellerList.size() == 0) {
                ToastUtil.showToast("请选择入住人");
            //}
            //else if (selectedTravellerList.size() < unSelectRoomNum) {
             //   ToastUtil.showToast("请选择其他入住人");
            } else {
                // 处理多人状态
                goToSelectHomePage(select_type);
            }
        }

    }
    /**
     * 已经选择了入住人，进行最终的选房
     */
    private void goToSelectHomePage(int select_type) {
        Intent intent = new Intent(mContext, SelectHomeActivity.class);
        intent.putExtra("selectType", select_type);
        intent.putExtra("orderMainUuid", orderMainUuid);
        intent.putExtra("selectedTravellerList", selectedTravellerList);
        intent.putExtra("orderDetailUuid", orderDetailUuid);
        intent.putExtra("orderDetailUuidslist", orderDetailUuidslist);
        mContext.startActivity(intent);
    }


}
